#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import subprocess

def run_prg(cmd):
    cmd_result = subprocess.Popen(cmd,
                                  shell = True,
                                  stderr = subprocess.STDOUT,
                                  stdout = subprocess.PIPE).communicate()[0]
    #  print cmd_result
    return cmd_result

def get_git_version(base_path):

    ver_last_commit = run_prg("git show").split()
    current_ver_commit = ver_last_commit[ver_last_commit.index("commit") + 1]
    version = current_ver_commit

    diff = run_prg("git diff")
    if diff:
        raw_input("请先commit!!!")

    ver_list = run_prg("git tag").split()

    for lt in ver_list:
        v_show = run_prg("git show %s" % lt)
        v_list = v_show.split()
        v_commit = v_list[v_list.index("commit") + 1]
        if v_commit == current_ver_commit:
            version = lt

    return version

def get_hg_version(base_path):
    repo_dir = base_path + '/../'
    #print repo_dir
#    repo = hg.repository(ui.ui(), repo_dir)
    fctx = repo.filectx(repo_dir, 'tip')
    ctx = fctx.changectx()
    return str(ctx.rev())

def get_main_dir():
    """Return the script directory - whether we're frozen or not."""
    return os.path.abspath(os.path.dirname(sys.argv[0]))

def main(argv):
    base_dir = get_main_dir()
    # svn_version = get_svn_version(base_dir)
    try:
        hg_version = get_hg_version(base_dir)
    except:
        hg_version = get_git_version(base_dir)
    f_version_h = file(base_dir + "/prg_version.h", "w")
    #  f_version2_h = file(base_dir + "/wl_uart/Common/Source/prg_version.h", "w")
    v_str = "#define PRG_VERSION " + '"' + hg_version  + '"' + '\n'
    data_time_str = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    v_data_time_str = time.strftime('%Y%m%d_%H%M%S',time.localtime(time.time()))
    build_data = "#define BUILD_TIME " + '"' + data_time_str + '"' + '\n'
    build_data2 = "#define BUILD_TIME2 " + '"' + v_data_time_str + '"' + '\n'
    #sw_version = "#define SW_VERSION " + '"' + "V_1.1." + hg_version + "[" + v_data_time_str + "]"
    f_base_src = []
    f_base_src.insert(0, build_data)
    f_base_src.insert(0, build_data2)
    f_base_src.insert(0, v_str)
    f_version_h.writelines(f_base_src)
    f_version_h.close()
    #  f_version2_h.writelines(f_base_src)
    #  f_version2_h.close()

#    print argv
if __name__ == '__main__':
    main(sys.argv[1:])
